use tonic::{Request, Response, Status};
use crate::storage::LogStorage;
use crate::model::LogEntry;
use crate::proto::{LogRequest, LogResponse};

#[derive(Debug)]
pub struct LogService<S: LogStorage> {
    storage: S,
}

#[tonic::async_trait]
impl<S: LogStorage + Send + Sync + 'static> proto::LogService for LogService<S> {
    async fn log(
        &self,
        request: Request<LogRequest>,
    ) -> Result<Response<LogResponse>, Status> {
        let req = request.into_inner();
        
        // 验证请求
        if req.service_name.is_empty() || req.message.is_empty() {
            return Err(Status::invalid_argument("service_name and message are required"));
        }
        
        // 创建日志条目
        let entry = LogEntry {
            timestamp: Utc::now(),
            service_name: req.service_name,
            level: req.level.into(),
            message: req.message,
            metadata: req.metadata,
        };
        
        // 存储日志
        match self.storage.store(entry).await {
            Ok(_) => Ok(Response::new(LogResponse { success: true })),
            Err(e) => {
                error!("Failed to store log: {}", e);
                Err(Status::internal("Failed to store log"))
            }
        }
    }
}